﻿using System.Collections.Generic;
using System.ServiceModel;
using FlightSearchServer.TicketSellingService;

namespace FlightSearchServer
{
    internal static class TicketSellersDatabase
    {
        private static readonly Dictionary<string, ITicketSellingService> sellers = new Dictionary<string, ITicketSellingService>();

        public static void Add(string id, ITicketSellingService channel)
        {
            lock (sellers)
            {
                sellers[id] = channel;
            }
        }

        public static void Remove(string id)
        {
            lock (sellers)
            {
                ITicketSellingService channel;
                if (sellers.TryGetValue(id, out channel))
                {
                    try
                    {
                        ((IClientChannel) channel).Dispose();
                    }
                    catch (CommunicationException)
                    {
                        // :(
                    }
                }

                sellers.Remove(id);
            }
        }

        public static ITicketSellingService GetSellerChannel(string id)
        {
            lock (sellers)
            {
                ITicketSellingService channel;
                return sellers.TryGetValue(id, out channel) ? channel : null;
            }
        }

        public static IEnumerable<KeyValuePair<string, ITicketSellingService>> Sellers
        {
            get
            {
                lock (sellers)
                {
                    return new Dictionary<string, ITicketSellingService>(sellers); // make a copy for thread safety
                }
            }
        }
    }
}
